/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core.extend;

import com.inspur.edp.lcm.metadata.api.entity.MetadataCompilerContext;
import com.inspur.edp.lcm.metadata.api.entity.OperationEnum;
import com.inspur.edp.lcm.metadata.api.exception.ErrorCodes;
import com.inspur.edp.lcm.metadata.api.exception.LcmMavenDevException;
import com.inspur.edp.lcm.metadata.api.service.MetadataProjectService;
import com.inspur.edp.lcm.metadata.common.MavenUtils;
import com.inspur.edp.lcm.metadata.inner.api.utils.IdeLogUtils;
import com.inspur.edp.lcm.metadata.spi.BeforeCompileAction;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.commons.utils.StringUtils;

public class MavenBeforeCompileActionImpl implements BeforeCompileAction {
    private static MavenBeforeCompileActionImpl instance;
    public static MavenBeforeCompileActionImpl getInstance() {
        if (instance == null) {
            instance = new MavenBeforeCompileActionImpl();
        }
        return instance;
    }

    @Override
    public void validate(MetadataCompilerContext context) {
        String mavenHome = MavenUtils.getMavenHome();
        if (StringUtils.isEmpty(mavenHome)) {
            throw new LcmMavenDevException(ErrorCodes.ECP_MAVEN_DEV_0002);
        }
    }

    @Override
    public boolean isSourceFileChanged(MetadataCompilerContext context) {
        // java代码工程文件是否变化，检查整个code文件夹，包含src和target
        MetadataProjectService metadataProjectService = SpringBeanUtils.getBean(MetadataProjectService.class);
        String javaProjectPath = metadataProjectService.getJavaProjectPath(context.getProjectPath());
        boolean fileChanged = metadataProjectService.isFileChanged(javaProjectPath, OperationEnum.MAVEN);
        IdeLogUtils.setRestart(fileChanged);
        return fileChanged;
    }
}
